<template>
  <a-tabs v-model:activeKey="activeKey">
    <a-tab-pane key="1" tab="选择记录">
      <a-row :gutter="8">
        <a-col :span="10">
          <div>
            <a-range-picker
              v-model:value="state.drange"
              style="width: 320px"
              valueFormat="YYYY-MM-DD"
              :locale="locale"
              :placeholder="[$t('127'), $t('141')]"
            />
          </div>
          <div>
            <a-select
              v-model:value="state.committers"
              mode="multiple"
              style="width: 320px"
              :placeholder="$t('128')"
            >
              <a-select-option :value="uid">{{ $t("236") }}</a-select-option>
              <a-select-option
                v-for="item in appStore.otherUsers"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </div>
          <FveEditor
            ref="refFvee"
            :fields="lstFieldDefine"
            :inline="true"
          ></FveEditor>
          <a-button type="primary" @click="searchRecord">搜索</a-button>
        </a-col>
        <a-col :span="14">
          <a-flex justify="flex-end" align="center" style="margin-bottom: 4px">
            <a-input-search
              v-model:value="state.filter"
              :placeholder="$t('103')"
              @search="onSearch"
              @pressEnter="onSearch"
              style="width: 200px"
            />
          </a-flex>
          <a-table
            :columns="colModelData"
            :data-source="lstDisplay"
            bordered
            size="small"
            :row-selection="rowSelection"
            :pagination="false"
            :scroll="{ y: 800 }"
          >
          </a-table>
        </a-col>
      </a-row>
    </a-tab-pane>
    <a-tab-pane key="2" tab="新建记录" force-render>
      <RecordEditorForInlineModel
        :share-mode="false"
        :model-id="props.field.fieldType.C.provider"
        :fields="lstFieldDefine"
        @ok="searchRecord"
      ></RecordEditorForInlineModel>
    </a-tab-pane>
  </a-tabs>
</template>
<script setup>
import { reactive, computed, ref } from "vue";
import CommonDefine from "../CommonDefine";
import FveEditor from "@/component/query/FveEditor.vue";
import RecordEditorForInlineModel from "./RecordEditorForInlineModel.vue";

const appStore = CommonDefine.appStore();
const props = defineProps({ field: Object });
const emits = defineEmits(["change"]);
const state = reactive({
  multiSelect: false,
  selectedRowKeys: [],
  drange: [],
  committers: [],
  fvfs: [],
  filter: "",
});
const refFvee = ref();
const activeKey = ref("1");

const rowSelection = computed(() => {
  return {
    type: state.multiSelect ? "checkbox" : "radio",
    selectedRowKeys: state.selectedRowKeys,
    onChange: (selectedRowKeys) => {
      state.selectedRowKeys = selectedRowKeys;
      let recordId = selectedRowKeys[0];
      let rec = {};
      rec.value = parseInt(recordId);
      rec.display = lstDisplay.find((x) => {
        // console.log(x);
        return x.key == recordId;
      })[props.field.fieldType.C.displayField];
      emits("change", { fid: props.field.id, rec });
    },
  };
});

const lstFieldDefine = reactive([]);
const lstModelRecord = reactive([]);
const lstDisplay = reactive([]); //因为前端表格展示不支持.语法，弄一个专门放display的对象数组
const lstDisplayAll = reactive([]);

const colModelData = computed(() => {
  let ary = [];
  lstFieldDefine.forEach((df) => {
    let col = {
      dataIndex: df.id,
      title: df.label,
      type: df.fieldType.T,
    };
    if (
      df.fieldType.T == "FtString" ||
      df.fieldType.T == "FtDate" ||
      df.fieldType.T == "FtTime" ||
      df.fieldType.T == "FtDateTime" ||
      df.fieldType.T == "FtCode"
    ) {
      //字符串类型的排序
      col.sorter = (a, b) => {
        return a[df.id].localeCompare(b[df.id], "zh");
      };
      col.sortDirections = ["descend", "ascend"];
    } else if (
      df.fieldType.T == "FtInt" ||
      df.fieldType == "FtFloat" ||
      df.fieldType == "FtBool"
    ) {
      col.sorter = (a, b) => {
        return a[df.id] - b[df.id];
      };
      col.sortDirections = ["descend", "ascend"];
    }
    ary.push(col);
  });
  // ary.push({ dataIndex: "1", title: "更新日期" });
  return ary;
});

const _recArrayToDisplayArray = () => {
  state.filter = "";
  CommonDefine.clearArray(lstDisplayAll);
  CommonDefine.clearArray(lstDisplay);
  lstModelRecord.forEach((rec) => {
    let displayRecord = rec.display;
    displayRecord["key"] = displayRecord["0"];
    lstDisplayAll.push(displayRecord);
    lstDisplay.push(displayRecord);
  });
  /// 界面展示时，如果字段已经设置了值，将对应的记录选中
  // 未达预期，无法自动选中
  if (CommonDefine.useful(props.field.value)) {
    state.selectedRowKeys.push(props.field.value);
  }
};

const loadFields = () => {
  CommonDefine.runWithFieldCache(props.field.fieldType.C.provider, (fields) => {
    CommonDefine.clearArray(lstFieldDefine);
    fields.forEach((fieldDefine) => {
      lstFieldDefine.push(fieldDefine);
    });
    searchRecord();
  });
};

const searchRecord = () => {
  state.fvfs = refFvee.value.getFves();
  state.selectedRowKeys = [];
  CommonDefine.clearArray(lstModelRecord);
  CommonDefine.clearArray(lstDisplay);
  CommonDefine.apiPostArm(
    "/api/v1/record/page",
    {
      pageIndex: 1,
      pageSize: 100,
      modelId: props.field.fieldType.C.provider,
      filters: {
        drange: state.drange,
        committers: state.committers,
        fvfs: state.fvfs,
      },
    },
    (d) => {
      d.data.forEach((rec) => {
        lstModelRecord.push(rec);
      });
      _recArrayToDisplayArray();
    }
  );
};

const onSearch = () => {
  CommonDefine.clearArray(lstDisplay);
  if (CommonDefine.isStringValue(state.filter)) {
    let filteredArray = lstDisplayAll.filter((item) => {
      let hit = false;
      for (const key in item) {
        if (parseInt(key) > 10000) {
          if (item[key].indexOf(state.filter) > -1) {
            hit = true;
            break;
          }
        }
      }
      return hit;
    });
    filteredArray.forEach((item) => lstDisplay.push(item));
  } else {
    lstDisplayAll.forEach((item) => lstDisplay.push(item));
  }
};

defineExpose({ loadFields });
</script>
